package main

import (
	"log"
	"net/http"
	"os"
)

func main() {
	http.HandleFunc("/", handleRequest)
	http.HandleFunc("/healthz", healthCheck)

	version := os.Getenv("VERSION")
	if version == "" {
		version = "1.0.0" // 默认版本号
	}

	log.Printf("Starting server on :8080 with version %s", version)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// 将请求头写入响应头
	for key, values := range r.Header {
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}

	// 读取系统环境变量中的版本号并写入响应头
	w.Header().Set("X-VERSION", os.Getenv("VERSION"))

	// 记录访问日志
	log.Printf("Client IP: %s, HTTP Status Code: %d", r.RemoteAddr, http.StatusOK)

	w.WriteHeader(http.StatusOK)
}

func healthCheck(w http.ResponseWriter, r *http.Request) {
	// 健康检查，始终返回状态码 200
	w.WriteHeader(http.StatusOK)
	log.Printf("Health check requested by %s", r.RemoteAddr)
}
